import { getNowFormatDate, convertName, copyConfig } from './util'
import { getConfigure } from './config'


function getStoreLogPrimordial(name) {
    let curStoreDataArray = []
    try {
      const curStoreDataJSON = window.localStorage.getItem(name)
      if (curStoreDataJSON) {
        curStoreDataArray = JSON.parse(curStoreDataJSON)
      }
      return curStoreDataArray
    } catch (error) {
      console.error(error);
      return curStoreDataArray
    }
}

export class Logger {
  initConfig = {
    isShowConsole: false,
    logMaxLength: 100,
    name: '$$logger_base'
  }

  constructor(config = {}) {
    copyConfig(this.initConfig, config)
  }

  get config () {
    return this.initConfig.global ? getConfigure(): this.initConfig
  }


  /**
   * 存储日期
   * @param {*} option = { message, level }
   * @param option.message  必填 日志内容
   * @param option.level  非必填 日志提醒等级
   * @returns Boolean
   */
  setLog (option = {}) {
    const message = typeof option.message === 'object' ? JSON.stringify(option.message) : (option.message ?? '')
    const level = option.level ?? 'info'
    if(this.config.isShowConsole) {
      try {
        window.console[level](message) 
      } catch (error) {
        window.console.log(message)
      }
    }
    const newStoreData = {
      timer: getNowFormatDate(),
      message,
      level,
    }
    let curStoreDataArray = []
    const curStoreDataJSON = window.localStorage.getItem(this.config.name)
    if (curStoreDataJSON) {
      try {
        curStoreDataArray = JSON.parse(curStoreDataJSON)
      } catch (error) {
        log.error('[Logger Error] JSON.parse解析出错', error)
      }
    }
    if (curStoreDataArray.length >= this.config.logMaxLength) {
      curStoreDataArray.pop()
    }
    curStoreDataArray.unshift(newStoreData)
    window.localStorage.setItem(this.config.name, JSON.stringify(curStoreDataArray))
  }
  // 读取日志
  getLog (name) {
    const parseName = name ? convertName(name) : this.config.name
    return getStoreLogPrimordial(parseName)
  }

  info(message){
    this.setLog({message, level: 'info'})
  }
  
  warn(message){
    this.setLog({message, level: 'warn'})
  }
  
  error(message){
    this.setLog({message, level: 'error'})
  }

  // 静态方法 读取日志
  static getStoreLog (name) {
    const parseName = convertName(name)
    return getStoreLogPrimordial(parseName)
  }
}